package tcp

import (
	"fmt"
	"io"
	"net"
)

func NewServer(port int) {
	tcpAddr, err := net.ResolveTCPAddr("tcp4", fmt.Sprintf(":%d", port))
	if err != nil {
		fmt.Printf("resolve tcp address err:%v\n", err)
		return
	}

	listener, err := net.ListenTCP("tcp", tcpAddr)
	if err != nil {
		fmt.Printf("listen to port: %d err: %v\n", port, err)
		return
	}

	fmt.Printf("success start tcp server on listening port %d\n", port)

	for {
		fmt.Println("ready to accept a new conn")
		tcpConn, err := listener.AcceptTCP()
		if err != nil {
			fmt.Printf("accept tcp conn err: %v\n", err)
			continue
		}

		go handleConn(tcpConn)
	}

}

func handleConn(conn *net.TCPConn) {
	chunk := make([]byte, 1024)
	for {
		readLen, err := conn.Read(chunk)
		if err == io.EOF {
			fmt.Printf("read finished caused by client close the conn, err:%v\n", err)
			err := conn.Close()
			if err != nil {
				fmt.Printf("close conn err: %v\n", err)
			}
			break
		}

		if err != nil {
			fmt.Printf("read bytes error caused by err:%v\n", err)
			continue
		}

		if readLen == 0 {
			fmt.Printf("nothing read, maybe caused by client close the conn\n")
			continue
		}

		fmt.Printf("success read message: %s, len: %d\n", chunk[:readLen], readLen)

		_, _ = conn.Write(chunk[:readLen])
	}
}
